package com.lb.shopguide.ui.fragment.guide;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterGoodsList;
import com.lb.shopguide.adapter.AdapterMember;
import com.lb.shopguide.adapter.AdapterSelectMember;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.ChooseMemberBean;
import com.lb.shopguide.entity.MemberBean;
import com.lb.shopguide.entity.goods.GoodsInListBean;
import com.lb.shopguide.entity.network.PageBean;
import com.lb.shopguide.event.guide.MessageReadEvent;
import com.lb.shopguide.event.guide.SelectGoodsEvent;
import com.lb.shopguide.event.guide.SelectMemberEvent;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.im.session.SessionHelper;
import com.lb.shopguide.ui.view.search.MaterialSearchView;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.activity.MessageDetailActivity;
import com.lb.shopguide.ui.dialog.DialogSelectSku;
import com.lb.shopguide.ui.fragment.guide.order.FragmentSureOrder;
import com.lb.shopguide.util.json.JsonUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by kang on 2017/6/8.
 * 搜索模块，所有相关逻辑放在这里
 */

public class FragmentSearch extends BaseCommonFragment {
    @BindView(R.id.search_view)
    MaterialSearchView searchView;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;


    private AdapterGoodsList mAdapterGoods;
    private AdapterSelectMember mAdapterSelectMember;
    private AdapterMember mAdapterMember;

    private List<GoodsInListBean> mGoodsList;
    private List<ChooseMemberBean> mChooseMemberList;
    private List<MemberBean> mMemberList;
    private int mSearchType = AppConstant.SEARCH_GOODS;
    private int mGoodsSelectType = -1;
    private String mGoodsTypeCode;
    private String barcode;
    


    public static FragmentSearch newInstance(int type) {
        FragmentSearch fragment = new FragmentSearch();
        Bundle bundle = new Bundle();
        bundle.putInt(AppConstant.SEARCH_TYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static FragmentSearch newInstance(int type, int goodsSelectType, String typeCode) {
        FragmentSearch fragment = new FragmentSearch();
        Bundle bundle = new Bundle();
        bundle.putInt(AppConstant.SEARCH_TYPE, type);
        bundle.putInt(AppConstant.GOODS_SELECT_TYPE, goodsSelectType);
        bundle.putString(AppConstant.GOODS_TYPE_CODE, typeCode);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static FragmentSearch newInstance(int type, int goodsSelectType, String typeCode, String barcode) {
        FragmentSearch fragment = new FragmentSearch();
        Bundle bundle = new Bundle();
        bundle.putInt(AppConstant.SEARCH_TYPE, type);
        bundle.putInt(AppConstant.GOODS_SELECT_TYPE, goodsSelectType);
        if (!TextUtils.isEmpty(typeCode)) {
            bundle.putString(AppConstant.GOODS_TYPE_CODE, typeCode);
        }
        bundle.putString(AppConstant.BARCODE, barcode);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_search;
    }

    @Override
    public void initData() {
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        mMemberList = new ArrayList<>();
        mGoodsList = new ArrayList<>();
        mChooseMemberList = new ArrayList<>();
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.SEARCH_TYPE)) {//搜索啥
            mSearchType = bundle.getInt(AppConstant.SEARCH_TYPE);
        }
        if (bundle.containsKey(AppConstant.GOODS_SELECT_TYPE)) {
            mGoodsSelectType = bundle.getInt(AppConstant.GOODS_SELECT_TYPE);
        }
        if (bundle.containsKey(AppConstant.GOODS_TYPE_CODE)) {
            mGoodsTypeCode = bundle.getString(AppConstant.GOODS_TYPE_CODE);
        }
        if (bundle.containsKey(AppConstant.BARCODE)) {
            barcode = bundle.getString(AppConstant.BARCODE);
        }
    }

    @Override
    public void initView() {
        noDataView = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_view, (ViewGroup) mRecyclerView.getParent(), false);
        errorView = LayoutInflater.from(mContext).inflate(R.layout.layout_error_view, (ViewGroup) mRecyclerView.getParent(), false);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        if (mSearchType == AppConstant.SEARCH_GOODS) {
            mAdapterGoods = new AdapterGoodsList(R.layout.item_goods_management, mGoodsList);
            mRecyclerView.setAdapter(mAdapterGoods);
            mAdapterGoods.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    if (mGoodsList.size() > position) {
                        if (mGoodsSelectType == AppConstant.GOODS_SELECT_IN_CHECKOUT) {
                            DialogSelectSku dialogSelectSku = DialogSelectSku.getDialogSelectSku(mGoodsList.get(position));
                            dialogSelectSku.show(getFragmentManager(), getPageTag());
                        } else {
                            KeyboardUtils.hideSoftInput(_mActivity);
                            pop();
                            GoodsInListBean bean = mGoodsList.get(position);
                            bean.setStoreCode(mUserConfigManager.getStoreCode());
                            EventBus.getDefault().post(new SelectGoodsEvent(bean));
                        }
                    }
                }
            });
            mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).marginProvider(mAdapterGoods).paintProvider(mAdapterGoods).build());
        } else if (mSearchType == AppConstant.SEARCH_MEMBER) {
            mAdapterSelectMember = new AdapterSelectMember(R.layout.item_member_content, mChooseMemberList);
            mRecyclerView.setAdapter(mAdapterSelectMember);
            mAdapterSelectMember.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    KeyboardUtils.hideSoftInput(_mActivity);
                    popTo(FragmentSureOrder.class, false);
                    EventBus.getDefault().post(new SelectMemberEvent(mChooseMemberList.get(position)));
                }
            });
            mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).marginProvider(mAdapterSelectMember).paintProvider(mAdapterSelectMember).build());
        } else if (mSearchType == AppConstant.SEARCH_GUIDE_MEMBER) {
            mAdapterMember = new AdapterMember(R.layout.item_member, mMemberList);
            mRecyclerView.setAdapter(mAdapterMember);
            mAdapterMember.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, final int position) {
                    KeyboardUtils.hideSoftInput(_mActivity);
                    popTo(FragmentMain.class, false, new Runnable() {
                        @Override
                        public void run() {
                            MemberBean bean = mMemberList.get(position);
                            MessageDetailActivity.start(mContext, bean.getAppUserCode(), SessionHelper.getP2pCustomization(bean.getAppUserCode()), null);
                            EventBus.getDefault().post(new MessageReadEvent());
                        }
                    });

                }
            });
            mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).marginProvider(mAdapterMember).paintProvider(mAdapterMember).build());
        }


        initSearchViewListener();
        if (!TextUtils.isEmpty(barcode)) {
            onQuerySubmit(barcode);
        }
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) _mActivity).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    @Override
    public String getPageTag() {
        return FragmentSearch.class.getName();
    }

    private void initSearchViewListener() {
        searchView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String suggestion = searchView.getSuggestionAtPosition(position);
                onQuerySubmit(suggestion);
            }
        });
        searchView.getSearchEditText().setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                onQuerySubmit(searchView.getSearchEditText().getText().toString());
                return true;
            }
        });
//        searchView.setOnClearClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                onQuerySubmit("");
//            }
//        });
        searchView.setOnEditTextEmptyListener(new MaterialSearchView.OnEditTextEmptyListener() {
            @Override
            public void onEditTextEmpty() {
                mRecyclerView.setVisibility(View.GONE);
            }
        });
    }

    @OnClick(R.id.tv_search_back)
    void onSearchCancel() {
        KeyboardUtils.hideSoftInput(_mActivity);
        pop();
    }

    @Override
    public boolean onBackPressedSupport() {
        KeyboardUtils.hideSoftInput(getActivity());
        return super.onBackPressedSupport();
    }

    private void onQuerySubmit(String keyword) {
        searchView.setQuery(keyword, false);
        if (TextUtils.isEmpty(keyword)) {
            mRecyclerView.setVisibility(View.GONE);
        } else {
            searchView.saveQueryToDb(keyword, System.currentTimeMillis());
            searchView.dismissSuggestions();
            if (mSearchType == AppConstant.SEARCH_GOODS) {
                sendRequestGetGoodsList(keyword);
            } else if (mSearchType == AppConstant.SEARCH_MEMBER) {
                sendRequestGetMemberList(keyword);
            } else if (mSearchType == AppConstant.SEARCH_GUIDE_MEMBER) {
                sendRequestGetGuideMemberList(keyword);
            }
            mRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    private void bindEmpty() {

        mNoData = true;
        onRefresh();
    }


    public void onRefresh() {
        if (mSearchType == AppConstant.SEARCH_GOODS) {
            mGoodsList.clear();
            mAdapterGoods.setNewData(mGoodsList);
            mAdapterGoods.setEnableLoadMore(false);
            if (mError) {
                mAdapterGoods.setEmptyView(errorView);
                mError = false;
            } else {
                if (mNoData) {
                    mAdapterGoods.setEmptyView(noDataView);
                    mNoData = false;
                }
//            else {
//                refresh();
//            }
            }
        } else if (mSearchType == AppConstant.SEARCH_MEMBER) {
            mChooseMemberList.clear();
            mAdapterSelectMember.setNewData(mChooseMemberList);
            mAdapterSelectMember.setEnableLoadMore(false);
            if (mError) {
                mAdapterSelectMember.setEmptyView(errorView);
                mError = false;
            } else {
                if (mNoData) {
                    mAdapterSelectMember.setEmptyView(noDataView);
                    mNoData = false;
                }
            }
        } else if (mSearchType == AppConstant.SEARCH_GUIDE_MEMBER) {
            mMemberList.clear();
            mAdapterMember.setNewData(mMemberList);
            mAdapterMember.setEnableLoadMore(false);
            if (mError) {
                mAdapterMember.setEmptyView(errorView);
                mError = false;
            } else {
                if (mNoData) {
                    mAdapterMember.setEmptyView(noDataView);
                    mNoData = false;
                }
            }
        }
    }


    private void sendRequestGetMemberList(String keyword) {
        mChooseMemberList = new ArrayList<>();
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JsonArray jsonMembers = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                    if (jsonMembers.size() != 0) {
                        for (JsonElement obj : jsonMembers) {
                            ChooseMemberBean bean = JsonUtil.getGson().fromJson(obj, ChooseMemberBean.class);
                            mChooseMemberList.add(bean);
                        }
                        mAdapterSelectMember.setNewData(mChooseMemberList);
                    } else {
                        bindEmpty();
                    }
                }
            }
        };
        ApiMethodGuide.getMemberList(new SimpleLbObserver(listener, otherListener), mUserConfigManager.getStoreCode(), keyword, this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestGetGuideMemberList(String keyword) {
        mMemberList = new ArrayList<>();
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JsonArray jsonMembers = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                    if (jsonMembers.size() != 0) {
                        if (jsonMembers.size() != 0) {
                            for (JsonElement obj : jsonMembers) {
                                MemberBean bean = JsonUtil.getGson().fromJson(obj, MemberBean.class);
                                mMemberList.add(bean);
                            }
                            mAdapterMember.setNewData(mMemberList);
                        } else {
                            bindEmpty();
                        }
                    }
                }
            }
        };
        ApiMethodGuide.getGuideMemberList(new SimpleLbObserver(listener, otherListener), keyword, this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestGetGoodsList(String keyword) {
        mGoodsList = new ArrayList<>();
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    PageBean curPageBean = JsonUtil.getPageBeanFromMap(response.getReturnContent());
                    JsonArray jsonGoods = JsonUtil.getJsonArrayFromMap(curPageBean.getList());
                    if (jsonGoods.size() != 0) {
                        for (JsonElement obj : jsonGoods) {
                            GoodsInListBean bean = JsonUtil.getGson().fromJson(obj, GoodsInListBean.class);
                            mGoodsList.add(bean);
                        }
                        mAdapterGoods.setNewData(mGoodsList);
                    } else {
                        bindEmpty();
                    }
                }
            }
        };
        ApiMethodGuide.getGoodsListByCondition(new SimpleLbObserver(listener, otherListener), mUserConfigManager.getStoreCode(), mGoodsTypeCode, keyword, 1, 100, this, FragmentEvent.DESTROY_VIEW);
    }
}
